const db = require("../models");
const DAO = require("../dao/DAO");
const logger = require("../utils/utils.logger");
const md5 = require('js-md5');
const User = db.user;
const Village = db.village;
const Op = db.Op;

// 创建用户
exports.create = async (req, res, next) => {
  try {
    const pm = req.body;
    if (!pm.username) return res.sendResultAto(null, 605, '用户名不能为空')
    if (!pm.villageId) return res.sendResultAto(null, 605, '乡村不能为空')
    const params = { username: pm.username, villageId: pm.villageId, realname: pm.realname, role: 'user', password: md5('123456').toUpperCase() }
    // 判断是否存在
    const exist = await User.findOne({
      where: params
    });
    if (exist) {
      return res.sendResultAto(null, 500, '用户已存在')
    }
    // 新增
    await User.create(params)
    res.sendResultAto(null, 200, '添加成功！')
  } catch (error) {
    logger.error(error)
    next('服务器内部错误')
  }
};

// 查询用户
exports.findAll = async (req, res, next) => {
  try {
    // 查询非admin用户
    const list = await DAO.list(User, {
      params: {
        role: {
          [Op.ne]: 'admin',
        }
      },
      attributes: ['userId', 'username', 'realname'],
      include: { model: Village, attributes: ['villageName', 'villageId'] },
      sort: {
				prop: 'userId',
				order: 'desc',
			}
    }, null)
    res.sendResult(list)
  } catch (error) {
    logger.error(error)
    next('服务器内部错误')
  }
};


// 删除用户
exports.delete = async (req, res, next) => {
  try {
    const userId = req.params.id;
    // 请求验证
    if (!userId) return res.sendResult({ data: '', code: 605, message: "ID不能为空！" })
    const data = await User.destroy({
      where: {
        userId,
        role: {
          [Op.ne]: 'admin',
        }
      }
    })
    if (data) {
      res.sendResultAto(null, 200, '删除成功！')
    } else {
      res.sendResultAto(null, 500, '数据不存在')
    }
  } catch (error) {
    logger.error(error)
    next('服务器内部错误')
  }
};

// 登录
exports.login = ({ username, password }) => {
  return new Promise(async (resolve, reject) => {
    try {
      const data = await User.findOne({
        where: {
          username,
          password
        }
      });
      resolve(data)
    } catch (error) {
      logger.error(error.message)
      reject(error)
    }
  })
}



